<template>
  <view class="delivery-code">
    <!-- <image :src="path" class="code-img" /> -->
    <canvas canvas-id="delivery-code" class="code-img" />
    <view class="save-btn-wrap">
      <button @click="saveImg">保存</button>
    </view>
    <!-- <canvas ref="canvas" id="canvas" class="code-img"></canvas> -->
  </view>
</template>

<script>
import { mapGetters } from "vuex";
// import QRCode from "qrcode";
import uQRCode from "../../../js_sdk/Sansnn-uQRCode/uqrcode.js";
import { base64ToPath } from "image-tools";
import { qrcodeBaseUrl } from "@/config/index";
export default {
  data() {
    return {
      // url: "https://life.maiziit.cn/?sid"
      code: "",
    };
  },
  computed: {
    ...mapGetters({
      shopId: "shopId",
    }),
    url() {
      return `${qrcodeBaseUrl}/?sid=${this.shopId}`;
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      uQRCode.make({
        canvasId: "delivery-code",
        componentInstance: this,
        text: this.url,
        size: 250,
        margin: 10,
        backgroundColor: "#ffffff",
        foregroundColor: "#000000",
        fileType: "jpg",
        correctLevel: uQRCode.defaults.correctLevel,
        success: (res) => {
          this.code = res;
        },
      });
    },
    saveImg(w) {
      uni.canvasToTempFilePath({
        // x: 100,
        // y: 200,
        // width: 50,
        // height: 50,
        // destWidth: 100,
        // destHeight: 100,
        canvasId: "delivery-code",
        success: function (res) {
          // 在H5平台下，tempFilePath 为 base64
          console.log(res.tempFilePath);
          uni.saveImageToPhotosAlbum({
            // 将图片保存在手机
            filePath: res.tempFilePath, //保存的位置
            success: (res) => {
              uni.showToast({
                title: `二维码保存成功`,
                icon: "none",
              });
            },
            fail: (error) => {
              uni.showToast({
                title: `二维码保存失败`,
                icon: "none",
              });
              console.log("fail", error);
            },
          });
        },
      });
      // base64ToPath(this.code).then(path => {
      //   uni.saveImageToPhotosAlbum({
      //     // 将图片保存在手机
      //     filePath: path, //保存的位置
      //     success: res => {
      //       uni.showToast({
      //         title: `二维码保存成功`,
      //         icon: "none"
      //       });
      //     },
      //     fail: error => {
      //       console.log("fail", error);
      //     }
      //   });
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.delivery-code {
  // height: 500rpx;
  // width: 500rpx;
  background-color: #ffffff;
  padding: 50rpx;
  .code-img {
    height: 250px;
    width: 250px;
  }
}
</style>